package com.zhiwang.planet.ui.glide.transformation

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.util.Log
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.mvvm.binding.TAG
import java.security.MessageDigest


/**
 * 后台默认上传 两倍图( xhpi 切图)，现在为了适配，需要根据不同像素密度进行图片缩放
 */
object XhpiBitmapTransformation: BitmapTransformation() {

    val id = "XhpiBitmapTransformationFor"

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(id.toByteArray())
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {

        if (BuildConfig.DEBUG)
            Log.i(TAG, "transform: ${Resources.getSystem().displayMetrics.density} ${toTransform.width} ${toTransform.height}  $outWidth  $outHeight")

        val scale = Resources.getSystem().displayMetrics.density

        val s = scale / 2.0f

        val bitmapConfig = toTransform.config ?: Bitmap.Config.ARGB_8888

        val reUse = pool.get((s * toTransform.width).toInt(), (s * toTransform.height).toInt(), bitmapConfig)

        val matrix = Matrix()

        matrix.setScale(s, s)

        applyMatrix(toTransform, reUse, matrix)

        return reUse
    }


    override fun equals(other: Any?): Boolean {
        return other is XhpiBitmapTransformation
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }

    private val DEFAULT_PAINT = Paint(TransformationUtils.PAINT_FLAGS)

    private fun applyMatrix(inBitmap: Bitmap, targetBitmap: Bitmap,
                            matrix: Matrix) {
        try {
            val canvas = Canvas(targetBitmap)
            canvas.drawBitmap(inBitmap, matrix, DEFAULT_PAINT)
            canvas.setBitmap(null)
        } finally {

        }
    }

}

